// MulticastGroups.java - Maintains all datastructures of all 

import java.io.*;
import java.net.*;
import java.util.*;
import java.lang.StringBuffer;

/*
 Maintains two hashmaps ( DefaultGroups, UserGroups )
 - Functions implemented
 --- addDefaultGroups
 --- createUserGroup
 --- getNextMulticastIp
 --- listDefaultGroups

*/


public class MulticastGroups
{
 static int ipCounter = 1;
 static String lastAssignedIp = new String("239.230.1."+ ipCounter);

 static HashMap<String, String> DefaultGroups = new HashMap<String, String>();
 static HashMap<String, String> UserGroups = new HashMap<String, String>();

 static boolean addDefaultGroups()
 {
   try{
      
         DefaultGroups.put( "USC", new String(getNextMulticastIp()) );
         ipCounter++;
         lastAssignedIp = new String("239.230.1."+ipCounter);
    
         DefaultGroups.put( "UCLA", new String(getNextMulticastIp()) );
         ipCounter++;
         lastAssignedIp = new String("239.230.1."+ipCounter);

         DefaultGroups.put( "MIT", new String(getNextMulticastIp()) );
         ipCounter++;
         lastAssignedIp = new String("239.230.1."+ipCounter);

     }catch( Exception e ) {e.printStackTrace();} 
 return true;
 
 }//end addDefaultGroups()


 static String listDefaultGroups()
 {
    Set myHashSet = DefaultGroups.entrySet();
    Iterator i = myHashSet.iterator();
    StringBuffer groupsListBuffer = new StringBuffer();    

    while(i.hasNext())
    {
      Map.Entry currentEntry = (Map.Entry)i.next();
      //System.out.println(currentEntry.getKey()+" : "+currentEntry.getValue());
      groupsListBuffer.append(currentEntry.getKey()+" : "+currentEntry.getValue()+" \n"); 
    }//end while   

  return groupsListBuffer.toString();

 }//End listDefaultGroups


 static void createUserGroup()
 {






 }//End createUserGroup()


 static String getNextMulticastIp() throws IOException
 {
   while(true)
   { 
    InetAddress address = InetAddress.getByName(lastAssignedIp);
    try {
        //System.out.println("checking IP :"+lastAssignedIp);
        address = InetAddress.getByName(lastAssignedIp);
        if(!address.isReachable( 1000 ))
        {
          //System.out.println(lastAssignedIp+" available");
          return lastAssignedIp;
        }else{
          //System.out.println(lastAssignedIp+" not available");
          ipCounter++;
          lastAssignedIp = new String("239.230.1." + ipCounter);
        }
     }
     catch (UnknownHostException e) {
       System.err.println("Unable to lookup Server");
     }
     catch (IOException e) {
       System.err.println("Unable to reach Server");
     }

   }//End while(1)

 }//End getNextMulticastIp

}//End MulticastGroups


/* TODO's

 1. The IP address that are checked are not reserverd untill the time that 
    the client actually uses them. Thus there could be some one else who
    would bind to that IP and it would become unavaialbe for us.

*/
